package com.cloud.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * 支付控制层
 *
 * @author : z_sz
 * @date : 2020-06-05 13:54
 **/
@RestController
@RequestMapping("/pay")
public class PaymentController {

    /**
     * 计次
     */
    private static int countNum = 0;

    @GetMapping("/payGoods")
    //=====服务熔断
    @HystrixCommand(fallbackMethod = "payGoodsFallBackMethod",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),// 是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),// 请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), // 时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),// 失败率达到多少后跳闸
    })
    public String payGoods(@RequestParam("goodsName") String goodsName,@RequestParam("price") Double price) {
        // 创造一个熔断效果(10次访问，失败6次，失败率达到60%即开启熔断，窗口期时间之后，熔断器半开，并慢慢恢复)
        countNum++;
        if(countNum <= 10 && countNum >= 3){
            throw new RuntimeException("请求第一次失败："+countNum);
        }
        if(StringUtils.isEmpty(goodsName) || 0 >= price) {
            return "参数异常";
        }
        return "购买："+goodsName+"成功，已支付金额："+price+"元;商店：8001";
    }

    public String payGoodsFallBackMethod(@RequestParam("goodsName") String goodsName,@RequestParam("price") Double price) {
        return "当前服务器正忙，请稍后再试";
    }

}
